<!-- src/view/Register.vue -->
<template>
  <div class="register-container">
    <div class="register-form">
      <h2>用户注册</h2>

      <!-- 注意：ref 用字符串，和 Login.vue 一致 -->
      <el-form
          ref="registerFormRef"
          :model="registerForm"
          :rules="registerRules"
          class="register-ruleForm"
      >
        <el-form-item prop="username">
          <el-input
              v-model="registerForm.username"
              placeholder="请输入用户名"
              prefix-icon="User"
              clearable
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              show-password
          />
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="请确认密码"
              prefix-icon="Lock"
              show-password
          />
        </el-form-item>

        <el-form-item prop="email">
          <el-input
              v-model="registerForm.email"
              placeholder="请输入邮箱"
              prefix-icon="Message"
              clearable
          />
        </el-form-item>

        <!-- 验证码：与 Login.vue 同步 -->
        <el-form-item prop="captcha">
          <div class="captcha-container">
            <el-input
                v-model="registerForm.captcha"
                placeholder="请输入验证码"
                prefix-icon="Key"
                style="flex: 1; margin-right: 10px;"
                clearable
            />
            <img
                v-if="captchaImg"
                :src="captchaImg"
                alt="验证码"
                @click="loadCaptcha"
                class="captcha-img"
                @error="handleImageError"
            />
            <div v-else class="captcha-placeholder">加载中...</div>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              @click="onSubmit"
              :loading="loading"
              class="register-button"
          >
            注册
          </el-button>
        </el-form-item>

        <el-form-item class="login-link">
          <el-button type="text" @click="goToLogin">
            已有账号？立即登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import registerApi from '../api/registerApi.js' // 与现有命名保持一致

const router = useRouter()
const registerFormRef = ref()

// 表单数据（对齐 Login.vue：加入 captcha、key）
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  captcha: '',
  key: ''
})

// 加载状态 & 验证码图
const loading = ref(false)
const captchaImg = ref('')
const isCaptchaLoading = ref(false)

// ---------- 与 Login.vue 对齐的工具函数 ----------
const handleImageError = (e) => {
  // 只有在确实有图片但加载失败时才提示错误
  if (captchaImg.value) {
    console.error('验证码图片加载失败:', e)
    console.log('当前captchaImg值:', captchaImg.value)
    // 不再显示错误消息，因为图片可能已经成功显示
    // ElMessage.error('验证码图片加载失败')
  }
}

function cleanBase64String(base64Str) {
  if (!base64Str) return base64Str
  return base64Str.replace(/[^A-Za-z0-9+/=]/g, '')
}

function isValidBase64(str) {
  if (typeof str !== 'string') return false
  const base64Regex = /^[A-Za-z0-9+/]*={0,2}$/
  return base64Regex.test(str)
}

// 获取验证码（与 Login.vue 同步：兼容两种后端结构）
const loadCaptcha = async () => {
  isCaptchaLoading.value = true
  try {
    const res = await registerApi.captcha()
    console.log('注册-验证码响应:', res)

    if (res && res.code === 200) {
      if (!res.data) {
        console.error('验证码数据为空')
        ElMessage.error('验证码数据异常：服务器未返回有效数据')
        return
      }

      let base64Data = null
      let keyData = null

      if (res.data.base64 && res.data.key) {
        base64Data = res.data.base64
        keyData = res.data.key
      } else if (res.data.data && res.data.data.base64 && res.data.data.key) {
        base64Data = res.data.data.base64
        keyData = res.data.data.key
      }

      if (base64Data && keyData) {
        const cleaned = cleanBase64String(base64Data)
        if (isValidBase64(cleaned)) {
          captchaImg.value = 'data:image/png;base64,' + cleaned
          registerForm.key = keyData
          console.log('注册-验证码加载成功')
        } else {
          console.error('非法的Base64字符串:', cleaned)
          ElMessage.error('验证码数据异常：Base64格式错误')
        }
      } else {
        console.error('验证码数据结构不正确:', res.data)
        ElMessage.error('验证码数据异常：数据结构不正确')
      }
    } else {
      const errorMsg = res?.msg || '获取验证码失败'
      console.error('获取验证码失败:', errorMsg)
      ElMessage.error(errorMsg)
    }
  } catch (err) {
    console.error('获取验证码异常:', err)
    ElMessage.error('获取验证码异常: ' + (err.message || '请检查网络连接'))
  } finally {
    isCaptchaLoading.value = false
  }
}

// ---------- 校验规则 ----------
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 16, message: '用户名长度应在3-16位之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码长度应在6-16位之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

// 跳转登录
const goToLogin = () => {
  router.push('/login')
}

// 提交注册（对齐 Login.vue：失败/异常后刷新验证码）
const onSubmit = async () => {
  console.log('注册按钮被点击')

  if (!registerFormRef.value) {
    console.error('registerFormRef 未正确绑定')
    return
  }

  registerFormRef.value.validate(async (valid) => {
    console.log('表单验证结果:', valid)
    if (!valid) {
      ElMessage.warning('请检查表单填写是否正确')
      return
    }

    loading.value = true
    try {
      const registerData = {
        username: registerForm.username,
        password: registerForm.password, // 明文提交，让后端处理加密与校验
        email: registerForm.email,
        captcha: registerForm.captcha,
        key: registerForm.key,

        // 你原先的默认字段（可按后端需要保留/调整）
        role: 'user',
        status: 1,
        is_deleted: 0
      }

      console.log('发送注册请求数据:', registerData)
      const res = await registerApi.register(registerData)
      console.log('注册响应:', res)

      if (res && res.code === 200) {
        // 清除可能存在的旧登录状态
        localStorage.removeItem("token")
        localStorage.removeItem("userInfo")

        ElMessage.success('注册成功，请登录')
        router.push('/login')
      } else {
        ElMessage.error(res?.msg || '注册失败')
        loadCaptcha() // 失败后刷新验证码
      }
    } catch (err) {
      console.error('注册失败:', err)
      ElMessage.error('注册失败: ' + (err.message || '请检查网络连接'))
      loadCaptcha() // 异常也刷新验证码
    } finally {
      loading.value = false
    }
  })
}

// 挂载时加载验证码（与 Login.vue 同步）
onMounted(() => {
  loadCaptcha()
})
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f2f5;
}

.register-form {
  width: 400px;
  padding: 40px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  text-align: center;
}

.register-form h2 {
  margin-bottom: 30px;
  color: #333;
}

.captcha-container {
  display: flex;
  align-items: center;
}

.captcha-img {
  height: 40px;
  cursor: pointer;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  display: block;
}

.captcha-placeholder {
  height: 40px;
  line-height: 40px;
  width: 100px;
  text-align: center;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  color: #999;
}

.register-button {
  width: 100%;
}

.login-link {
  text-align: center;
  margin-top: 10px;
}
</style>